package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceShadowDataVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.stream.Collectors;
import java.time.ZoneOffset;

/**
 * 设备Service业务层处理
 * 
 * @author laoYe
 * @date 2025-05-30
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步华为云平台产品
     */
    @Override
    public void syncProductList() {
        // 查询请求对象
        ListProductsRequest request = new ListProductsRequest();
        // 执行查询
        ListProductsResponse response = client.listProducts(request);
        // 获取华为云平台上的产品列表
        List<ProductSummary> products = response.getProducts();
        // 转成vo, 原来的华为返回的产品对象，数据太多了，只需要id与name即可
        List<ProductVo> productList = products.stream().map(p -> new ProductVo(p.getProductId(), p.getName()))
                .collect(Collectors.toList());
        // 存入redis
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, productList);
    }

    /**
     * 查询所有产品信息
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        List<ProductVo> productList = (List<ProductVo>)redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        return productList;
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void register(DeviceDto deviceDto) {
        //1、设备名称不能重复
        Long count = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if(count > 0){
            throw new ServiceException("设备名称不能重复");
        }
        //2、设备标识码不能重复
        count = lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()).count();
        if(count > 0){
            throw new ServiceException("设备标识码不能重复");
        }
        //3、同一个位置不能绑定同一类产品设备
        count = lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .count();
        if(count > 0){
            throw new ServiceException("该位置或老人已经绑定过同一类产品设备了！");
        }
        //4、请求华为云注册设备
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        // 设置设备的属性
        AddDevice addDevice = new AddDevice();
        addDevice.setDeviceName(deviceDto.getDeviceName());
        addDevice.setNodeId(deviceDto.getNodeId());
        addDevice.setProductId(deviceDto.getProductKey());
        //授权信息，密钥
        AuthInfo authInfo = new AuthInfo();
        // 设备的密钥
        String secret = UUID.fastUUID().toString(true);
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        addDeviceRequest.setBody(addDevice);
        try {
            AddDeviceResponse response = client.addDevice(addDeviceRequest);
            //5、保存设备信息到数据库
            Device device = BeanUtil.toBean(deviceDto, Device.class);
            device.setIotId(response.getDeviceId());//iotId
            device.setSecret(secret);

            save(device);
        } catch (Exception e) {
            log.error("注册设备失败", e);
            throw new ServiceException("注册设备失败！请稍候重试");
        }

    }

    /**
     * 查询设备的详细信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getDeviceInfo(String iotId) {
        //1、通过iotId查询设备信息
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        if(device == null){
            throw new ServiceException("设备不存在");
        }
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //2、查询华为云平台上的设备数据
        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
        showDeviceRequest.setDeviceId(iotId);
        try {
            ShowDeviceResponse response = client.showDevice(showDeviceRequest);
            vo.setDeviceStatus(response.getStatus());
            String activeTimeStr = response.getActiveTime();
            if(StringUtils.isNotEmpty(activeTimeStr)){
                LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);

                //日期时区转换, 当前所在的时区
                activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        // 转时区,获取系统中的时区
                        .withZoneSameInstant(ZoneId.systemDefault())
                        .toLocalDateTime();
                vo.setActiveTime(activeTime);
            }
        } catch (Exception e) {
            log.error("查询云平台上的设备数据失败", e);
            throw new ServiceException("查询云平台上的设备数据失败");
        }
        //3、组装到vo，返回
        return vo;
    }

    /**
     * 查询设备上报的最新数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceShadowDataVo> queryServiceProperties(String iotId) {
        List<DeviceShadowDataVo> voList = new ArrayList<>();
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        try {
            ShowDeviceShadowResponse response = client.showDeviceShadow(request);
            //System.out.println(response.toString());
            List<DeviceShadowData> list = response.getShadow();
            for (DeviceShadowData deviceShadowData : list) {
                // 上报的数据，里面属性名与值
                DeviceShadowProperties reported = deviceShadowData.getReported();
                LinkedHashMap<String, Object> propertiesData = (LinkedHashMap)reported.getProperties();
                // 上报数据的时间
                String eventTime = reported.getEventTime();
                LocalDateTime activeTime = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
                //日期时区转换, 当前所在的时区
                LocalDateTime activeDateTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        // 转时区,获取系统中的时区
                        .withZoneSameInstant(ZoneId.systemDefault())
                        .toLocalDateTime();
                // 把map中的每个数据转成List
                voList = propertiesData.entrySet().stream().map(entry -> {
                    DeviceShadowDataVo vo = new DeviceShadowDataVo();
                    vo.setEventTime(activeDateTime);
                    vo.setFunctionId(entry.getKey());
                    vo.setValue(entry.getValue().toString());
                    return vo;
                }).collect(Collectors.toList());
            }
        } catch (Exception e) {
            log.error("查询设备最新数据失败",e);
            throw new ServiceException("查询设备最新数据失败");
        }
        return voList;
    }

    /**
     * 通过productKey查询产品的详情
     *
     * @param productKey
     */
    @Override
    public List<ServiceCapability> queryProductInfo(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        try {
            ShowProductResponse response = client.showProduct(request);
            return response.getServiceCapabilities();
            /*for (ServiceCapability serviceCapability : response.getServiceCapabilities()) {
                System.out.println(serviceCapability.getProperties());
            }

            System.out.println(response.toString());*/
        } catch (Exception e) {
            log.error("通过productKey【{}】查询产品的详情",productKey, e);
        }
        return List.of();
    }

    public static void main(String[] args) {
        System.out.println("ZoneId.systemDefault() = " + ZoneId.systemDefault());
    }
}
